#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.db.models import Sum
from rest_framework import serializers

from vehicle.consts import RedisKey
from vehicle.map import AMapApi
from vehicle.models import VehicleInfoModel, VehicleFaultInfoModel, VehicleFaultLogModel, VehicleFenceModel, VehicleMoveInfoModel
from application.settings import redis_cli
from dvadmin.utils.serializers import CustomModelSerializer


class VehicleInfoModelSerializer(CustomModelSerializer):
    """
    序列化器
    """
    road_desc = serializers.SerializerMethodField()
    road_accident = serializers.SerializerMethodField()

    class Meta:
        model = VehicleInfoModel
        fields = "__all__"

    def get_road_desc(self, obj):
        if obj.start_point and obj.end_point:
            traffic = AMapApi().get_traffic_status('圆明园西路')
            return traffic.get('description', '无')
        return '无'

    def get_road_accident(self, obj):
        if obj.start_point and obj.end_point:
            traffic = AMapApi().get_traffic_status('圆明园西路')
            # 计算道路得分
            expedite = traffic.get('expedite', '100.00%')
            expedite = int(expedite[:-4])

            drive_score_cnt = VehicleMoveInfoModel.objects.filter(score__gt=0, vehicle_vin=obj.vin).count()
            if not drive_score_cnt:
                return '无法评分'

            # 计算驾驶得分
            drive_score = VehicleMoveInfoModel.objects.filter(score__gt=0, vehicle_vin=obj.vin).aggregate(Sum('score'))['score__sum'] / drive_score_cnt
            drive_score = int(drive_score)

            # 危险系数 = 100 - (驾驶得分.avg * 0.5 + 道路德分 * 0.5)
            accident = 100 - (drive_score * 0.5 + expedite * 0.5)
            if 0 < accident <= 30:
                return '低风险'
            elif 30 < accident <= 60:
                return '中风险‘'
            elif 60 < accident <= 100:
                return '高风险'
        else:
            return '无法评分'


class VehicleInfoModelCreateUpdateSerializer(CustomModelSerializer):
    """
    创建/更新时的列化器
    """
    def handle_drive_path(self, validated_data):
        start_point = validated_data.get("start_point") 
        end_point = validated_data.get("end_point") 
        if start_point and end_point:
            distance = AMapApi().get_distance(start_point, end_point)
            validated_data['distance'] = distance
        return validated_data

    def set_vin_fence(self, vin, fence_id):
        redis_cli.set(RedisKey.get_vin_fence_key(vin), fence_id)

    def create(self, validated_data):
        vin = validated_data['vin']
        fence_id = validated_data.get("vehicle_fence", '')
        self.set_vin_fence(vin, fence_id)
        validated_data = self.handle_drive_path(validated_data)
        return super().create(validated_data)

    def update(self, instance, validated_data):
        vin = validated_data['vin']
        fence_id = validated_data.get("vehicle_fence", '')
        self.set_vin_fence(vin, fence_id)
        validated_data = self.handle_drive_path(validated_data)
        return super().update(instance, validated_data)

    class Meta:
        model = VehicleInfoModel
        fields = '__all__'


class VehicleFaultInfoModelSerializer(CustomModelSerializer):
    """
    序列化器
    """

    class Meta:
        model = VehicleFaultInfoModel
        fields = "__all__"


class VehicleFaultInfoModelCreateUpdateSerializer(CustomModelSerializer):
    """
    创建/更新时的列化器
    """

    class Meta:
        model = VehicleFaultInfoModel
        fields = '__all__'


class VehicleFaultLogModelSerializer(CustomModelSerializer):
    """
    序列化器
    """

    class Meta:
        model = VehicleFaultLogModel
        fields = "__all__"


class VehicleFaultLogModelCreateUpdateSerializer(CustomModelSerializer):
    """
    创建/更新时的列化器
    """

    class Meta:
        model = VehicleFaultLogModel
        fields = '__all__'


class VehicleFenceModelSerializer(CustomModelSerializer):
    """
    序列化器
    """

    class Meta:
        model = VehicleFenceModel
        fields = "__all__"


class VehicleFenceModelCreateUpdateSerializer(CustomModelSerializer):
    """
    创建/更新时的列化器
    """

    def create(self, validated_data):
        redis_cli.hdel(RedisKey.get_fence_info(), validated_data.get("id"))
        return super().create(validated_data)

    def update(self, instance, validated_data):
        redis_cli.hdel(RedisKey.get_fence_info(), instance.id)
        return super().update(instance, validated_data)

    class Meta:
        model = VehicleFenceModel
        fields = '__all__'


class VehicleMoveInfoModelSerializer(CustomModelSerializer):
    """
    序列化器
    """

    class Meta:
        model = VehicleMoveInfoModel
        fields = "__all__"


class VehicleMoveInfoModelCreateUpdateSerializer(CustomModelSerializer):
    """
    创建/更新时的列化器
    """

    def create(self, validated_data):
        return super().create(validated_data)

    def update(self, instance, validated_data):
        return super().update(instance, validated_data)

    class Meta:
        model = VehicleMoveInfoModel
        fields = '__all__'
